<template>
  <view class="bg-white min-h-100vh p-4">
    <u-form label-position="left" ref="uForm" :model="formData" :rules="rules">
      <u-form-item
        label="警员"
        prop="officerId"
        border-bottom
        required
        @click="showOfficers = true"
      >
        <picker
          :show="showOfficers"
          :range="officers"
          range-key="label"
          header-text="请选择警员"
          @change="handleSelectOfficer"
        >
          <u-input
            v-model="formData.officerName"
            disabled
            disabledColor="#ffffff"
            placeholder="请选择警员"
            border="none"
          ></u-input>
        </picker>
        <u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>
      <u-form-item
        label="外观分数"
        label-width="80"
        prop="appearanceScore"
        border-bottom
        required
      >
        <u-rate v-model="formData.appearanceScore" :count="10"></u-rate>
      </u-form-item>
      <u-form-item
        label="内务分数"
        label-width="80"
        prop="uniformScore"
        border-bottom
        required
      >
        <u-rate v-model="formData.uniformScore" :count="10"></u-rate>
      </u-form-item>
      <u-form-item
        label="评语"
        label-position="top"
        prop="comments"
        border-bottom
        required
      >
        <textarea
          v-model="formData.comments"
          class="mt-10px p-0"
          type="textarea"
          placeholder="请输入"
        ></textarea>
      </u-form-item>
      <u-form-item label="照片" label-position="top" prop="fileList">
        <view class="mt-10px">
          <u-upload
            v-if="isCreate"
            width="100"
            height="100"
            multipl
            :file-list="formData.fileList"
            :max-count="3"
            @afterRead="afterRead($event)"
            @delete="deletePic($event)"
          ></u-upload>
          <view v-else class="flex justify-between items-center">
            <image
              v-for="(img, index) in formData.fileList"
              :key="index"
              :src="'https://api.gamestrial.com/xcx_file/' + img"
              mode="aspectFill"
              class="w-100px h-100px rounded-10px"
            ></image>
          </view>
        </view>
      </u-form-item>
    </u-form>

    <view v-if="userInfo.Permission === 'admin'" class="bottom-box">
      <u-button
        v-if="isCreate"
        text="确认"
        color="#386ee8"
        :throttle-time="600"
        :loading="btnLoading"
        @click="handleSubmit"
      />
      <u-button
        v-else
        text="删除"
        color="#F56C6C"
        :throttle-time="600"
        :loading="btnLoading"
        @click="handleDel"
      />
    </view>
  </view>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'

import {
  deleteAppearanceApi,
  getAppearanceDetailByIdApi,
  postAppearanceApi
} from '../index/service'
import dayjs from 'dayjs'
import { getOfficersRecordsApi, uploadApi } from './service'
import { showModal, showToast, sleep } from '@/utils/helper/uniHelper'
import { map } from 'lodash-es'
import { userStore } from '@/store'

@Component({ name: 'Form' })
export default class Form extends Vue {
  get userInfo(): any {
    return userStore.userInfo || {}
  }
  btnLoading = false
  showOfficers = false
  formData = {
    officerName: '',
    officerId: '',
    appearanceScore: null,
    uniformScore: null,
    comments: '',
    fileList: [] as any
  }
  officers: {
    label: string
    id: string
  }[] = []
  rules = {
    officerId: {
      type: 'string',
      required: true,
      message: '请选择警员',
      trigger: ['blur', 'change']
    },
    appearanceScore: {
      type: 'number',
      required: true,
      message: '请评分',
      trigger: ['change']
    },
    uniformScore: {
      type: 'number',
      required: true,
      message: '请评分',
      trigger: ['change']
    },
    comments: {
      type: 'string',
      required: true,
      message: '请填写评语',
      trigger: ['blur', 'change']
    }
  }
  radio = ''
  switchVal = false

  uForm: any = null
  handleSelectOfficer({ detail: { value } }: any) {
    this.formData.officerId = String(this.officers[value].id)
    this.formData.officerName = String(this.officers[value].label)
    ;(this.$refs.uForm as any).validateField('officerId')
    this.showOfficers = false
  }

  async handleSubmit() {
    try {
      await (this.$refs.uForm as any).validate()
      uni.showLoading({ title: '提交中' })
      this.btnLoading = true
      const { officerId, appearanceScore, uniformScore, comments, fileList } =
        this.formData
      await postAppearanceApi({
        OfficerID: officerId,
        CheckDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        AppearanceScore: appearanceScore,
        UniformScore: uniformScore,
        Comments: comments,
        FileList: map(fileList, 'url').join(',')
      })
      await showToast({
        title: '提交成功',
        icon: 'none'
      })
      uni.navigateBack()
    } finally {
      uni.hideLoading()
      this.btnLoading = false
    }
  }

  async handleDel() {
    const { confirm } = await showModal({
      content: '确认删除？'
    })
    if (confirm) {
      try {
        this.btnLoading = true
        await deleteAppearanceApi({
          RecordId: (this as any).$mp.query.RecordId
        })
        uni.navigateBack()
      } finally {
        this.btnLoading = false
      }
    }
  }

  deletePic(event: any) {
    this.formData.fileList.splice(event.index, 1)
  }

  async afterRead(event: any) {
    console.log(' ', event)
    let lists: any = [].concat(event.file)
    lists.forEach((item: any) => {
      const items = {
        ...item,
        status: 'uploading',
        message: '上传中'
      }
      this.formData.fileList.push(items)
    })
    const arr = this.formData.fileList
    for (let i = 0; i < arr.length; i++) {
      if (arr[i]?.status === 'uploading') {
        wx.uploadFile({
          url: 'https://api.gamestrial.com/upload/upload',
          filePath: arr[i].thumb,
          name: 'file',
          formData: {
            filename: arr[i].name
          },
          success: (uploadRes) => {
            console.log(' uploadRes', uploadRes)
            let item = arr[i]
            this.formData.fileList.splice(
              i,
              1,
              Object.assign(item, {
                status: 'success',
                message: '',
                url: JSON.parse(uploadRes.data)?.file?.filename
              })
            )
          }
        })
      }
    }
  }

  isCreate = true
  onReady() {
    ;(this.$refs.uForm as any).setRules(this.rules)
  }

  async onLoad() {
    const { type, view, RecordId } = (this as any).$mp.query
    if (view) {
      this.isCreate = false
      const { records } = await getAppearanceDetailByIdApi({
        RecordId
      })
      this.formData = {
        officerName: records.Name,
        officerId: records.OfficerID,
        appearanceScore: records.AppearanceScore,
        uniformScore: records.UniformScore,
        comments: records.Comments,
        fileList: records.FileList?.split(',') || []
      }
    }
    switch (type) {
      case '0':
        uni.setNavigationBarTitle({ title: '新增仪容仪表' })
        break
    }
    const { records } = await getOfficersRecordsApi()
    this.officers = records.map((item: any) => {
      return {
        label: item.Name,
        id: item.OfficerID
      }
    })
  }
}
</script>

<style lang="scss" scoped></style>
